<template>
  <div>
    <div class="report-info-container">
      <!-- 顶部提示信息 -->
      <el-alert
        title="请如实填写资质信息,我们将在1-3个工作日内完成审核"
        type="info"
        :closable="false"
        show-icon
      />

      <!-- 审核状态卡片 -->
      <el-card v-if="hasSubmitted" class="status-card" shadow="hover">
        <template #header>
          <div class="status-header">
            <h3>认证审核状态</h3>
            <el-tag :type="getStatusType(formData.authStatus)">
              {{ getStatusText(formData.authStatus) }}
            </el-tag>
          </div>
        </template>
        <div class="status-content">
          <el-timeline>
            <el-timeline-item
              :type="getTimelineItemType(1)"
              timestamp="提交申请"
              :hollow="formData.authStatus === '0'"
            >
              已提交认证申请
              <div class="time-info">{{ formData.createTime }}</div>
            </el-timeline-item>
            <el-timeline-item
              :type="getTimelineItemType(2)"
              timestamp="审核中"
              :hollow="formData.authStatus === '0'"
            >
              {{ getAuditStatusText() }}
            </el-timeline-item>
            <el-timeline-item
              :type="getTimelineItemType(3)"
              timestamp="审核完成"
              :hollow="!['1', '2'].includes(formData.authStatus)"
            >
              {{ getAuditResultText() }}
              <template v-if="formData.authStatus === '2'">
                <div class="reject-reason">拒绝原因：{{ formData.rejectionReason }}</div>
                <el-button type="primary" @click="handleReapply" size="small">
                  重新提交
                </el-button>
              </template>
            </el-timeline-item>
          </el-timeline>
        </div>
      </el-card>

      <!-- 原有的表单内容，添加条件显示 -->
      <div v-if="!hasSubmitted || isReapplying">
        <el-card class="main-form" shadow="hover">
          <template #header>
            <div class="form-header">
              <h3>农户资质认证</h3>
              <el-tag v-if="formData.status" :type="getStatusType(formData.status)">
                {{ getStatusText(formData.status) }}
              </el-tag>
            </div>
          </template>

          <el-form
            ref="formRef"
            :model="formData"
            :rules="rules"
            label-width="120px"
            class="report-form"
          >
            <!-- 基本信息部分 -->
            <div class="form-section">
              <h4 class="section-title">基本信息</h4>
              <el-row :gutter="20">
                <el-col :span="12">
                  <el-form-item label="姓名" prop="realName">
                    <el-input v-model="formData.realName" placeholder="请输入真实姓名" />
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="身份证号" prop="idCardNumber">
                    <el-input
                      v-model="formData.idCardNumber"
                      placeholder="请输入身份证号"
                    />
                  </el-form-item>
                </el-col>
              </el-row>

              <el-row :gutter="20">
                <el-col :span="12">
                  <el-form-item label="联系电话" prop="phone">
                    <el-input v-model="formData.phone" placeholder="请输入联系电话" />
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="种植年限" prop="farmingYears">
                    <el-input-number
                      v-model.number="formData.farmingYears"
                      :min="3"
                      :max="100"
                      placeholder="请输入从事种植年限"
                    />
                  </el-form-item>
                </el-col>
              </el-row>
            </div>

            <!-- 农场信息部分 -->
            <div class="form-section">
              <h4 class="section-title">农场信息</h4>
              <el-row :gutter="20">
                <el-col :span="12">
                  <el-form-item label="农场名称" prop="farmName">
                    <el-input v-model="formData.farmName" placeholder="请输入农场名称" />
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="农场执照编号" prop="farmLicense">
                    <el-input
                      v-model="formData.farmLicense"
                      placeholder="请输入农场执照编号"
                      clearable
                    >
                      <template #append>
                        <el-tooltip
                          content="如有营业执照或其他登记证书，请填写证书编号"
                          placement="top"
                        >
                          <el-icon><QuestionFilled /></el-icon>
                        </el-tooltip>
                      </template>
                    </el-input>
                  </el-form-item>
                </el-col>
              </el-row>

              <el-row :gutter="20">
                <el-col :span="12">
                  <el-form-item label="农场地址" prop="farmAddress">
                    <el-cascader
                      v-model="formData.farmRegion"
                      :options="regionOptions"
                      :props="{ value: 'areaId', label: 'areaName' }"
                      placeholder="请选择所在地区"
                    />
                    <el-input
                      v-model="formData.farmAddress"
                      placeholder="请输入详细地址"
                      style="margin-top: 10px"
                    />
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="农场面积(亩)" prop="farmArea">
                    <el-input-number
                      v-model.number="formData.farmArea"
                      :min="0"
                      :precision="2"
                      placeholder="请输入农场面积"
                    />
                  </el-form-item>
                </el-col>
              </el-row>

              <el-form-item label="主要作物" prop="mainCrops">
                <el-select
                  v-model="formData.mainCrops"
                  multiple
                  placeholder="请选择主要种植作物"
                >
                  <el-option
                    v-for="item in cropOptions"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select>
              </el-form-item>
            </div>

            <!-- 资质证明部分 -->
            <div class="form-section">
              <h4 class="section-title">资质证明</h4>

              <!-- 身份证照片上传 -->
              <el-row :gutter="20">
                <el-col :span="12">
                  <el-form-item label="身份证正面" prop="idCardImageFront">
                    <el-upload
                      class="id-card-uploader"
                      :headers="{ Authorization: 'Bearer ' + getToken() }"
                      :action="uploadUrl"
                      :before-upload="beforeUpload"
                      :on-success="(res) => handleUploadSuccess(res, 'idCardImageFront')"
                      :on-error="handleUploadError"
                      :show-file-list="false"
                    >
                      <img
                        v-if="formData.idCardImageFront"
                        :src="formData.idCardImageFront"
                        class="upload-image"
                      />
                      <div v-else class="upload-placeholder">
                        <el-icon class="upload-icon"><Plus /></el-icon>
                        <div class="upload-text">点击上传身份证正面照片</div>
                      </div>
                    </el-upload>
                    <div class="upload-tip">请上传清晰的身份证人像面照片</div>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="身份证反面" prop="idCardImageBack">
                    <el-upload
                      class="id-card-uploader"
                      :headers="{ Authorization: 'Bearer ' + getToken() }"
                      :action="uploadUrl"
                      :before-upload="beforeUpload"
                      :on-success="(res) => handleUploadSuccess(res, 'idCardImageBack')"
                      :on-error="handleUploadError"
                      :show-file-list="false"
                    >
                      <img
                        v-if="formData.idCardImageBack"
                        :src="formData.idCardImageBack"
                        class="upload-image"
                      />
                      <div v-else class="upload-placeholder">
                        <el-icon class="upload-icon"><Plus /></el-icon>
                        <div class="upload-text">点击上传身份证反面照片</div>
                      </div>
                    </el-upload>
                    <div class="upload-tip">请上传清晰的身份证国徽面照片</div>
                  </el-form-item>
                </el-col>
              </el-row>

              <!-- 农场照片上传 -->
              <el-form-item label="农场实景照片" prop="farmPhotos">
                <el-upload
                  class="farm-photos-uploader"
                  :headers="{ Authorization: 'Bearer ' + getToken() }"
                  :action="uploadUrl"
                  :before-upload="beforeUpload"
                  :on-success="(res) => handleUploadSuccess(res, 'farmPhotos')"
                  :on-error="handleUploadError"
                  :on-exceed="handleExceed"
                  multiple
                  list-type="picture-card"
                  :limit="6"
                  :file-list="formData.farmPhotos"
                >
                  <el-icon class="upload-icon"><Plus /></el-icon>
                  <template #file="{ file }">
                    <div class="upload-list-item">
                      <img class="upload-list-item-image" :src="file.url" alt="" />
                      <div class="upload-list-item-actions">
                        <el-icon
                          class="upload-list-item-preview"
                          @click="handlePictureCardPreview(file)"
                        >
                          <ZoomIn />
                        </el-icon>
                        <el-icon
                          class="upload-list-item-delete"
                          @click="handleRemove(file)"
                        >
                          <Delete />
                        </el-icon>
                      </div>
                    </div>
                  </template>
                </el-upload>
                <div class="upload-tip">请上传农场实景照片，最多6张</div>
              </el-form-item>

              <!-- 其他证明材料上传 -->
              <el-form-item label="其他证明材料" prop="otherDocs">
                <el-upload
                  class="other-docs-uploader"
                  :action="uploadUrl"
                  :headers="{ Authorization: 'Bearer ' + getToken() }"
                  :before-upload="beforeOtherDocsUpload"
                  :on-success="(res) => handleUploadSuccess(res, 'otherDocs')"
                  :on-error="handleUploadError"
                  :on-remove="handleRemove"
                  multiple
                  :limit="10"
                  :file-list="formData.otherDocs"
                >
                  <el-button type="primary">
                    <el-icon><Upload /></el-icon>
                    <span>上传文件</span>
                  </el-button>
                  <template #tip>
                    <div class="upload-tip">
                      <p>可上传以下证明材料（选填，最多10份）：</p>
                      <ul>
                        <li>农业相关证书（技术员证书、培训证书等）</li>
                        <li>产品认证（无公害、绿色食品、有机认证等）</li>
                        <li>经营资质（家庭农场认定、合作社证书等）</li>
                      </ul>
                      <p>支持格式：PDF、JPG、PNG，单个文件不超过10MB</p>
                    </div>
                  </template>
                </el-upload>
              </el-form-item>
            </div>

            <!-- 提交按钮 -->
            <div class="form-actions">
              <el-button type="primary" @click="submitForm">提交审核</el-button>
              <el-button @click="resetForm">重置</el-button>
            </div>
          </el-form>
        </el-card>
      </div>
    </div>

    <!-- 添加图片预览对话框 -->
    <el-dialog v-model="previewVisible" title="预览">
      <img :src="previewUrl" alt="Preview Image" style="width: 100%" />
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from "vue";
import { Plus, ZoomIn, Delete, Upload } from "@element-plus/icons-vue";
import { ElMessage } from "element-plus";
import { getToken } from "@/utils/auth";
import { addAuth } from "@/api/farmer/auth";
import { getAuthStatus } from "@/api/farmer/authExt";
import { getSystemArea } from "@/api/system/common";
// 表单数据
const formRef = ref(null);
const previewVisible = ref(false);
const formData = reactive({
  realName: "",
  idCardNumber: "",
  phone: "",
  farmingYears: 0,
  farmName: "",
  farmArea: 0,
  farmRegion: [],
  farmAddress: "",
  farmLicense: "",
  mainCrops: [],
  idCardImageFront: "",
  idCardImageBack: "",
  farmPhotos: [],
  otherDocs: [],
  status: "", // 审核状态
  authStatus: "", // 新增认证状态
  createTime: "", // 新增提交时间
  rejectionReason: "", // 新增拒绝原因
});
// 地区码表
const regionOptions = ref([]);
// 获取地区码表
const getSysArea = async () => {
  const res = await getSystemArea()
  if (res.code === 200) {
    regionOptions.value = res.data
  }
}

// 表单验证规则
const rules = {
  realName: [
    { required: true, message: "请输入姓名", trigger: "blur" },
    { min: 2, max: 20, message: "长度在 2 到 20 个字符", trigger: "blur" },
  ],
  idCardNumber: [
    { required: true, message: "请输入身份证号", trigger: "blur" },
    {
      pattern: /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/,
      message: "请输入正确的身份证号",
      trigger: "blur",
    },
  ],
  phone: [
    { required: true, message: "请输入联系电话", trigger: "blur" },
    { pattern: /^1[3-9]\d{9}$/, message: "请输入正确的手机号码", trigger: "blur" },
  ],
  farmingYears:[
    { required: true, message: "请输入种植年限", trigger: "blur" },
    { type: 'number', min: 3, message: "种植年限必须大于3年", trigger: "blur" },
  ],
  farmName: [
    { required: true, message: "请输入农场名称", trigger: "blur" },
    { min: 2, max: 20, message: "长度在 2 到 20 个字符", trigger: "blur" },
  ],
  farmLicense: [
    { required: true, message: "请输入农场执照编号", trigger: "blur" },
  ],
  farmAddress: [
    { required: true, message: "请输入农场地址", trigger: "blur" },
  ],
  farmArea: [
    { required: true, message: "请输入农场面积", trigger: "blur" },
    { type: 'number', min: 1, message: "农场面积必须大于0", trigger: "blur" },
  ],
  mainCrops: [
    { required: true, message: "请选择主要作物", trigger: "blur" },
  ],
  idCardImageFront: [
    { required: true, message: "请上传身份证正面照", trigger: "blur" },
  ],
  idCardImageBack: [
    { required: true, message: "请上传身份证反面照", trigger:"blur" },
  ],
  // 农场实景照片
  farmPhotos:[
  { required: true, message: "请上传农场实景照片", trigger:"blur" },
  ]
  // ... 其他验证规则
};

// 作物选项
const cropOptions = [
  { value: "rice", label: "水稻" },
  { value: "wheat", label: "小麦" },
  { value: "corn", label: "玉米" },
  { value: "vegetable", label: "蔬菜" },
  { value: "fruit", label: "水果" },
];
const handleExceed = () => {
  ElMessage.error("最多上传6张照片");
};
const handleRemove = (file, fileList) => {
  console.log(file, fileList);
};
// 获取状态类型
const getStatusType = (status) => {
  const statusMap = {
    '0': 'warning',   // 待审核
    '1': 'success',   // 已通过
    '2': 'danger'     // 已拒绝
  }
  return statusMap[status] || 'info'
}

// 获取状态文本
const getStatusText = (status) => {
  const statusMap = {
    '0': '待审核',
    '1': '已通过',
    '2': '已拒绝'
  }
  return statusMap[status] || '未提交'
}

// 文件上传相关方法
const uploadUrl = import.meta.env.VITE_APP_BASE_API + "/common/upload";

const beforeUpload = (file) => {
  const isImage = file.type.startsWith("image/");
  const isLt2M = file.size / 1024 / 1024 < 2;

  if (!isImage) {
    ElMessage.error("只能上传图片文件!");
    return false;
  }
  if (!isLt2M) {
    ElMessage.error("图片大小不能超过 2MB!");
    return false;
  }
  return true;
};

const handleUploadSuccess = (res, field) => {
  if (res.code === 200) {
    if (Array.isArray(formData[field])) {
      formData[field].push(res.url);
    } else {
      formData[field] = res.url;
    }
    ElMessage.success("上传成功");
  } else {
    ElMessage.error("上传失败");
  }
};

const handleUploadError = () => {
  ElMessage.error("上传失败，请重试");
};

// 表单提交
const submitForm = async () => {
  if (!formRef.value) return;

  await formRef.value.validate(async (valid) => {
    if (valid) {
      const res = await addAuth(formData);
      if (res.code === 200) {
        ElMessage.success("提交成功，请等待审核");
        hasSubmitted.value = true;
        isReapplying.value = false;
        formData.authStatus = "0"; // 设置为待审核状态
        formData.createTime = new Date().toLocaleString();
      } else {
        ElMessage.error("提交失败，请重试");
      }
    }
  });
};

// 重置表单
const resetForm = () => {
  if (!formRef.value) return;
  formRef.value.resetFields();
  formData.idCardFront = "";
  formData.idCardBack = "";
  formData.farmPhotos = [];
  formData.otherDocs = [];
};

// 其他证明材料上传前的验证
const beforeOtherDocsUpload = (file) => {
  // 支持的文件类型
  const allowedTypes = ["application/pdf", "image/jpeg", "image/png"];
  const isValidType = allowedTypes.includes(file.type);
  // 文件大小限制为10MB
  const isLt10M = file.size / 1024 / 1024 < 10;

  if (!isValidType) {
    ElMessage.error("只能上传PDF、JPG、PNG格式的文件!");
    return false;
  }
  if (!isLt10M) {
    ElMessage.error("文件大小不能超过 10MB!");
    return false;
  }
  return true;
};

// 添加新的响应式变量
const hasSubmitted = computed(() => {
  return formData.authStatus !== '3'
})

const isReapplying = ref(false)

// 获取时间线项目类型
const getTimelineItemType = (step) => {
  const status = formData.authStatus
  if (status === '0') {
    return step === 1 ? 'success' : step === 2 ? 'warning' : ''
  } else if (status === '1') {
    return 'success'
  } else if (status === '2') {
    return step === 3 ? 'danger' : 'success'
  }
  return ''
}

// 获取审核状态文本
const getAuditStatusText = () => {
  const status = formData.authStatus
  if (status === '0') {
    return '正在审核中，请耐心等待'
  } else if (status === '1') {
    return '审核已通过'
  } else if (status === '2') {
    return '审核未通过'
  }
  return ''
}

// 获取审核结果文本
const getAuditResultText = () => {
  const status = formData.authStatus
  if (status === '1') {
    return '恭喜您，认证审核已通过！'
  } else if (status === '2') {
    return '很抱歉，您的认证申请未通过审核。'
  }
  return '等待审核完成'
}

// 重新申请
const handleReapply = () => {
  isReapplying.value = true;
  // 清空表单数据，保留基本信息
  const basicInfo = {
    realName: formData.realName,
    idCardNumber: formData.idCardNumber,
    phone: formData.phone
  };
  Object.assign(formData, {
    ...basicInfo,
    farmingYears: 0,
    farmName: '',
    farmArea: 0,
    farmRegion: [],
    farmAddress: '',
    farmLicense: '',
    mainCrops: [],
    idCardImageFront: '',
    idCardImageBack: '',
    farmPhotos: [],
    otherDocs: [],
    authStatus: null,
    rejectionReason: null,
    createTime: null
  });
};

onMounted(async () => {
  // 先获取地区码表
  getSysArea()

  try {
    const res = await getAuthStatus();
    if (res.code === 200) {
      Object.assign(formData, res.data);
      if (res.data.authStatus) {
        isReapplying.value = false;
      }
    }
  } catch (error) {
    ElMessage.error('获取认证状态失败');
    console.error('获取认证状态失败:', error);
  }
});


</script>

<style lang="scss" scoped>
.report-info-container {
  padding: 20px;

  .main-form {
    margin-top: 20px;
  }

  .form-header {
    display: flex;
    justify-content: space-between;
    align-items: center;

    h3 {
      margin: 0;
      color: #303133;
    }
  }

  .form-section {
    margin-bottom: 30px;
    padding: 20px;
    background: #f8f9fa;
    border-radius: 4px;

    .section-title {
      margin: 0 0 20px;
      padding-left: 10px;
      border-left: 4px solid #409eff;
      color: #303133;
    }
  }

  // 身份证上传样式
  .id-card-uploader {
    :deep(.el-upload) {
      width: 360px;
      border: 1px dashed #d9d9d9;
      border-radius: 6px;
      overflow: hidden;
      cursor: pointer;
      position: relative;
      transition: border-color 0.3s;

      &:hover {
        border-color: #409eff;
      }
    }

    .upload-placeholder {
      width: 360px;
      height: 220px;
      display: flex;
      flex-direction: column;
      justify-content: center;
      align-items: center;
      background: #fafafa;

      .upload-icon {
        font-size: 32px;
        color: #8c939d;
        margin-bottom: 12px;
      }

      .upload-text {
        font-size: 14px;
        color: #606266;
      }
    }

    .upload-image {
      display: block;
      width: 360px;
      height: 220px;
      object-fit: contain;
      background: #fafafa;
    }
  }

  // 农场照片上传样式
  .farm-photos-uploader {
    :deep(.el-upload--picture-card) {
      width: 148px;
      height: 148px;
      margin: 0 8px 8px 0;
    }

    :deep(.el-upload-list--picture-card) {
      .el-upload-list__item {
        width: 148px;
        height: 148px;
      }
    }

    .upload-list-item {
      position: relative;
      width: 100%;
      height: 100%;

      .upload-list-item-image {
        width: 100%;
        height: 100%;
        object-fit: cover;
      }

      .upload-list-item-actions {
        position: absolute;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        display: flex;
        justify-content: center;
        align-items: center;
        background: rgba(0, 0, 0, 0.5);
        opacity: 0;
        transition: opacity 0.3s;

        .el-icon {
          color: #fff;
          font-size: 20px;
          cursor: pointer;
          margin: 0 6px;

          &:hover {
            transform: scale(1.1);
          }
        }
      }

      &:hover .upload-list-item-actions {
        opacity: 1;
      }
    }
  }

  // 其他证明材料上传样式
  .other-docs-uploader {
    :deep(.el-upload-list) {
      margin-top: 10px;
    }

    .upload-tip {
      font-size: 12px;
      color: #909399;
      margin-top: 8px;
      line-height: 1.6;

      ul {
        margin: 4px 0;
        padding-left: 20px;

        li {
          margin-bottom: 4px;
        }
      }

      p {
        margin: 4px 0;

        &:last-child {
          color: #f56c6c;
        }
      }
    }
  }

  .form-actions {
    text-align: center;
    margin-top: 40px;
  }

  // 调整上传提示文字位置
  .upload-tip {
    font-size: 12px;
    color: #909399;
    margin-top: 8px;
    line-height: 1.4;
    padding-left: 4px;
  }

  // 调整表单项间距
  .el-form-item {
    margin-bottom: 24px;
  }

  // 调整行间距
  .el-row {
    margin-bottom: 16px;

    &:last-child {
      margin-bottom: 0;
    }
  }
}

// 预览对话框样式
:deep(.el-dialog__body) {
  text-align: center;

  img {
    max-width: 100%;
    max-height: 70vh;
    object-fit: contain;
  }
}

// 添加新的样式
.status-card {
  margin: 20px 0;
}

.status-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.status-header h3 {
  margin: 0;
}

.status-content {
  padding: 20px;
}

.time-info {
  font-size: 12px;
  color: #999;
  margin-top: 5px;
}

.reject-reason {
  color: #f56c6c;
  margin: 10px 0;
  font-size: 14px;
}

.el-timeline-item {
  padding-bottom: 20px;
}
</style>
